package com.qbw.app.module.home.fragment;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.http.okhttp.HttpTask;
import com.lib.util.ResUtil;
import com.lib.util.ScreenUtil;
import com.lib.util.ToastUtil;
import com.qbw.actionmanager.ActionManager;
import com.qbw.app.Constant;
import com.qbw.app.Event;
import com.qbw.app.EventConstant;
import com.qbw.app.R;
import com.qbw.app.action.AddVehicleAction;
import com.qbw.app.action.DeleteVehicleAction;
import com.qbw.app.action.EditVehicleAction;
import com.qbw.app.action.MapChangedAction;
import com.qbw.app.action.UnitChangedAction;
import com.qbw.app.databinding.HomeFragmentBinding;
import com.qbw.app.manager.LocationManager;
import com.qbw.app.model.Location;
import com.qbw.app.model.TravelGps;
import com.qbw.app.model.Vehicle;
import com.qbw.app.model.VehicleHomeInfo;
import com.qbw.app.model.Weather;
import com.qbw.app.module.common.fragment.CommonFragment;
import com.qbw.app.module.common.util.Gps;
import com.qbw.app.module.common.util.HttpRequestUtil;
import com.qbw.app.module.common.util.PositionUtil;
import com.qbw.app.module.common.util.UniversalToastUtil;
import com.qbw.app.module.home.adapter.HomeAdapter;
import com.qbw.app.module.home.adapter.HomeViewType;
import com.qbw.app.module.home.holder.HomeActionHolder;
import com.qbw.app.module.home.holder.HomeBatteryMilleageHolder;
import com.qbw.app.module.home.holder.HomeCurrentVehicleHolder;
import com.qbw.app.module.home.holder.HomeLocationHolder;
import com.qbw.app.module.home.holder.HomeStatussHolder;
import com.qbw.app.module.home.holder.HomeTravelHolder;
import com.qbw.app.module.home.holder.HomeWaringMessageHolder;
import com.qbw.app.module.vehicle.VehicleDataBindingAdapter;
import com.qbw.app.module.vehicle.activity.VehicleLocationActivity;
import com.qbw.app.module.vehicle.activity.VehicleWarningActivity;
import com.qbw.app.module.vehicle.popwindow.VehicleSelectPopWindow;
import com.qbw.app.request.impl.CommonRequest;
import com.qbw.app.request.impl.UserRequest;
import com.lib.util.SPUtils;
import com.qbw.core.model.ViewType;
import com.qbw.core.observable.ObservableInt;
import com.qbw.l.L;
import com.qbw.spm.P;
import com.tbox.tbsdk.TBoxSDK;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;

import static com.qbw.app.Constant.KEY_MAP;
import static com.qbw.app.Constant.KEY_VEHICLE;
import static com.qbw.app.Constant.MAP_BAIDU;
import static com.qbw.app.Constant.MAP_DEFAULT;
import static com.qbw.app.Constant.MAP_GOOGLE;
import static com.qbw.app.module.home.adapter.HomeViewType.VT_ACTION;
import static com.qbw.app.module.home.adapter.HomeViewType.VT_CURRENT_VEHICLE;
import static com.qbw.app.module.home.adapter.HomeViewType.VT_LAST_TRAVEL;
import static com.qbw.app.module.home.adapter.HomeViewType.VT_LOCATION;
import static com.qbw.app.module.home.adapter.HomeViewType.VT_STATUS_ITEMS;
import static com.qbw.app.module.home.holder.HomeActionHolder.getmBtConnectStatusListener;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_HOME_INFO_V;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_LAST_TRAVEL;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_LOCATION;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_VEHICLE_LIST;

/*
 *
 * @author QBW
 * @date 2019/8/17
 */
public class HomeFragment extends CommonFragment<HomeFragmentBinding> implements HomeTravelHolder.Listener, ActionManager.Listener,
        HttpTask.CallBack,View.OnClickListener, OnMapReadyCallback {

    private HomeAdapter mAdapter;
    private Handler mHandler = new Handler();
    private Vehicle.Response responseVehicle;
    private List<Integer> mSortedHeaderViewTypes = new ArrayList<>();
    private Location location;
    private CompositeDisposable compositeDisposable;//轮询
    private VehicleHomeInfo homeInfo;
    private final int COUNT_LOOP = 5;
    private GoogleMap mGoogleMap;
    private Vehicle mVehicle;
    private float mBaiduInitScale = 15F;
    private float mGoogleInitScale = 15F;
    private ObservableInt mSecond = new ObservableInt(-1);
    private int mCount = COUNT_LOOP;
    private android.location.Location mCurrentLocation;
    private Overlay mBaiduMarker;
    private Marker mGoogleMarker;
    private TBoxSDK tBoxSDK;
    private HomeActionHolder.BtConnectStatusListener mBtConnectStatusListener;


    private static final String KEY_GPS_DATA = VehicleLocationActivity.class.getName() + "_key_gps_data";
    public static HomeFragment createInstance() {
        HomeFragment ins = new HomeFragment();
        return ins;
    }


    /**
     * 事件响应方法
     * 接收消息
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event) {
        switch (event.getAction()) {
            case EventConstant.MAP_SWITCH:
                initMap();
                break;
        }

    }


    @Override
    protected int getLayoutResId() {
        return R.layout.home_fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        LocationManager.getInstance().getLastLocation();
        tBoxSDK = TBoxSDK.getInstance(getContext());
//        mSortedHeaderViewTypes.add(HomeViewType.VT_CURRENT_VEHICLE);
//        mSortedHeaderViewTypes.add(HomeViewType.VT_LOCATION);
//        mSortedHeaderViewTypes.add(HomeViewType.VT_BATTERY_MILLEAGE);
        mSortedHeaderViewTypes.add(HomeViewType.VT_ACTION);
        mSortedHeaderViewTypes.add(VT_STATUS_ITEMS);
//        mSortedHeaderViewTypes.add(HomeViewType.VT_WARNING_INFO);
        getVehicleList();
        compositeDisposable = new CompositeDisposable();
        mBinding.rcv.setLayoutManager(new LinearLayoutManager(getActivity()));
        mBinding.rcv.setItemAnimator(null);
        mBinding.rcv.addItemDecoration(new InnerDecoration(getActivity()));
        mAdapter = new HomeAdapter(getActivity(), this);
        mBinding.rcv.setAdapter(mAdapter);
        mActionManager.addInterestedAction(this, VehicleSelectPopWindow.SelectedVehicleChangedAction.class);
        mActionManager.addInterestedAction(this, MapChangedAction.class);
        mActionManager.addInterestedAction(this, UnitChangedAction.class);
        mActionManager.addInterestedAction(this, DeleteVehicleAction.class);
        mActionManager.addInterestedAction(this, AddVehicleAction.class);
        mActionManager.addInterestedAction(this, EditVehicleAction.class);
        mBinding.llCurrentVehicle.setOnClickListener(this);
        mBinding.rlWarning.setOnClickListener(this);
        initMap();
    }


    private void scanBtDevice(String mac){
        tBoxSDK.startScanningDevice(mac,getActivity(), new TBoxSDK.DeviceScanningListener() {
            @Override
            public void onDeviceScanningFailed(int code) {

            }

            @Override
            public void onDeviceScanningListChanged(ArrayList<BluetoothDevice> devices) {
                connectDevice(devices.get(0));
            }

            @Override
            public void onDeviceScanningStopped(ArrayList<BluetoothDevice> devices) {

            }
        });
    }

    private boolean isBtConnectStatus;
    private void connectDevice(BluetoothDevice bluetoothDevice) {

        TBoxSDK.getInstance(getActivity()).connectDevice(bluetoothDevice, new TBoxSDK.DeviceConnectingListener() {
            @Override
            public void onDeviceConnected() {
//                ToastUtil.showToast(getContext(),bluetoothDevice.getName() + " 连接成功");
//
                isBtConnectStatus = true;
                mBtConnectStatusListener = getmBtConnectStatusListener();
                if(mBtConnectStatusListener !=null){
                    mBtConnectStatusListener.connectstatus(true);
                }
                TBoxSDK.getInstance(getActivity()).stopScanDevice();
                SPUtils.getInstance().put(Constant.KEY_BT_STATUS,true);


            }

            @Override
            public void onDeviceConnectFailed(int errorCode) {
//                ToastUtil.showToast(getContext(),bluetoothDevice.getName() + " 连接失败");
            }

            @Override
            public void onDeviceDisconnected(int errorCode) {
                isBtConnectStatus = false;
                SPUtils.getInstance().put(Constant.KEY_BT_STATUS,false);
//                ToastUtil.showToast(getContext(),bluetoothDevice.getName() + " 断开连接");
                mBtConnectStatusListener = getmBtConnectStatusListener();
                if(mBtConnectStatusListener !=null){
                    mBtConnectStatusListener.connectstatus(false);
                }

            }

            @Override
            public void onRssiUpdated(int rssi) {
            }

            @Override
            public void onDeviceStatusSync(TBoxSDK.LockStatus lockStatus, TBoxSDK.DefendStatus defendStatus, TBoxSDK.ACCStatus accStatus) {
//                showMessage("BLE 同步数据：" +
//                        "lockStatus [0x" + HexUtil.bytesToHexString(new byte[]{(byte)lockStatus.getStatus()}) + "], " +
//                        "defendStatus [0x" + HexUtil.bytesToHexString(new byte[]{(byte)defendStatus.getStatus()}) + "], " +
//                        "accStatus [0x" + HexUtil.bytesToHexString(new byte[]{(byte)accStatus.getStatus()}) + "]");
            }
        });
    }



    private void getVehicleList() {
        mGeneralManager.getRequestManager().getVehicleRequest().getVehicleList(this).execute();
    }

    private void getVehicleLocation(Vehicle vehicle) {
        mGeneralManager.getRequestManager()
                       .getVehicleRequest()
                       .getVehicleLocation(vehicle.getVehicleCode(), this)
                       .addExtraParam(KEY_VEHICLE, vehicle)
                       .execute();
    }

    private void getVehicleLastTravel(Vehicle vehicle) {
        mGeneralManager.getRequestManager()
                       .getVehicleRequest()
                       .getVehicleLastStroke(vehicle.getVehicleCode(), this)
                       .addExtraParam(KEY_VEHICLE, vehicle)
                       .execute();
    }

    private void getWeather() {
        //获取天气
        android.location.Location location = LocationManager.getInstance().getLastLocation();
        if (location != null) {
            mGeneralManager.getRequestManager()
                           .getCommonRequest()
                           .getWeather(location.getLatitude() + "",
                                       location.getLongitude() + "",
                                       "",
                                       this)
                           .execute();
        } else {
            L.GL.w("location = null");
        }
    }

    private void getHomeInfo(Vehicle vehicle) {
        if (vehicle != null) {
            mGeneralManager.getRequestManager()
                    .getVehicleRequest()
                    .getHomeInfoNm(vehicle.getVehicleCode(), this)
                    .addExtraParam(KEY_VEHICLE, vehicle)
                    .execute();
        }
    }


    /**
     * 十秒轮询一次是否登录成功
     */
    private void loopAtFixRate() {
        compositeDisposable.add(Observable.interval(1, 10, TimeUnit.SECONDS)
                .subscribe(new Consumer<Long>() {
                    @SuppressLint("MissingPermission")
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (mVehicle != null) {
                            if (!TextUtils.isEmpty(mVehicle.getVehicleCode())) {
                                TBoxSDK.getInstance(getActivity()).stopScanDevice();
                               getVehicleList();
                            }
                        }
                    }
                }));
    }


    @Override
    public void onHttpStart(HttpTask httpTask) {

    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        String method = httpTask.getMethod();
        if (METHOD_VEHICLE_LIST.equals(method)) {
            responseVehicle = (Vehicle.Response) entity;
//            int p = mAdapter.getHeaderPositionByViewType(VT_CURRENT_VEHICLE);
//            if (p == -1) {
//                mAdapter.addHeader(mAdapter.getHeaderPosition(VT_CURRENT_VEHICLE,
//                                                              mSortedHeaderViewTypes),
//                                   new HomeCurrentVehicleHolder.Data(response.getData(), null));
//            } else {
//                HomeCurrentVehicleHolder.Data data = (HomeCurrentVehicleHolder.Data) mAdapter.getHeader(
//                        p);
//                data.setVehicleList(response.getData());
//                mAdapter.updateHeader(p, data);
//            }
            mVehicle = responseVehicle.getData().getIndexVehicle();
            if (mVehicle != null) {
                mBinding.setVehicle(responseVehicle.getData().getIndexVehicle());
                SPUtils.getInstance().put(Constant.KEY_AES,hex2Str(mVehicle.getAesKey()));
                SPUtils.getInstance().put(Constant.KEY_TBOX,mVehicle.getTboxKey());
                SPUtils.getInstance().put(Constant.KEY_VEHICLECODE,mVehicle.getDeviceCode());
                Log.e("lander","    isBtConnectStatus=    "+isBtConnectStatus);
                if(!isBtConnectStatus){
                    if(mVehicle.getMac() != null && !"".equals(mVehicle.getMac())){
                        scanBtDevice(mVehicle.getMac());
                    }
                }
                getHomeInfo(mVehicle);
//                getWeather();
                getVehicleLocation(mVehicle);
//                getVehicleLastTravel(selectedVehicle);
            }
        } else if (METHOD_LOCATION.equals(method)) {
            Location.Response response = (Location.Response) entity;
            if(response.getData() !=null){
                location = response.getData();
                updateGpsSignal();
                //location.setVehicleCode((String) httpTask.getExtraParam(KEY_VEHICLE_CODE));
                Vehicle vehicle = (Vehicle) httpTask.getExtraParam(KEY_VEHICLE);
                location.setVehicleCode(vehicle.getVehicleCode());
                location.setVehicleNick(vehicle.getVehicleNick());
                mBinding.setLocation(location);
                mBinding.setSecond(mSecond);
                if(location == null){
                    mBinding.tvAddress.setText(getString(R.string.no_gps_location));
                }else{
                    mBinding.tvAddress.setText(location.getAddress());

                }
            }
            initMap();

//            if (location.getDrivingState() == VEHICLE_STATUS_DRIVING) {
//                mHandler.post(mCountTimeRunn);
//            }
//            if (location.getDrivingState() == Constant.VEHICLE_STATUS_INVALID) {
//                location.setAddress(ResUtil.getString(R.string.no_gps_data));
//            } else {
//                if (TextUtils.isEmpty(location.getAddress())) {
//                    location.setAddress(ResUtil.getString(R.string.no_gps_data));
//                }
//            }
        } else if (METHOD_LAST_TRAVEL.equals(method)) {
//            Travel.Response response = (Travel.Response) entity;
//            Travel travel = response.getData();
//            if (travel != null) {
//                Vehicle vehicle = (Vehicle) httpTask.getExtraParam(KEY_VEHICLE);
//                travel.setVehicle(vehicle);
//                mAdapter.removeChildByViewType(HomeViewType.VT_WAIT_NEW_TRAVEL);
//                int p = mAdapter.getChildPositionByViewType(VT_LAST_TRAVEL);
//                if (p == -1) {
//                    mAdapter.addChild(1, travel);
//                } else {
//                    mAdapter.updateChild(p, travel);
//                }
//            } else {
//                mAdapter.removeChildByViewType(VT_LAST_TRAVEL);
//                int p = mAdapter.getChildPositionByViewType(HomeViewType.VT_WAIT_NEW_TRAVEL);
//                if (p == -1) {
//                    mAdapter.addChild(1, new ViewType(HomeViewType.VT_WAIT_NEW_TRAVEL));
//                }
//            }
        } else if (method.equals(UserRequest.METHOD_UPDATE_INFO)) {
            //Vehicle indexVehicle = (Vehicle) httpTask.getExtraParam(KEY_VEHICLE);
            //mAdapter.notifyHeaderChanged(0);
            //getVehicleLocation(indexVehicle);
            //getVehicleLastTravel(indexVehicle);
            getVehicleList();
            closeLoadingDialog();
        } else if (method.equals(CommonRequest.METHOD_WEATHER)) {
            Weather.Response res = (Weather.Response) entity;
            Weather weather = res.getData();
            int p = mAdapter.getHeaderPositionByViewType(VT_CURRENT_VEHICLE);
            if (p == -1) {
                mAdapter.addHeader(mAdapter.getHeaderPosition(VT_CURRENT_VEHICLE,
                                                              mSortedHeaderViewTypes),
                                   new HomeCurrentVehicleHolder.Data(null, weather));
            } else {
                HomeCurrentVehicleHolder.Data data = (HomeCurrentVehicleHolder.Data) mAdapter.getHeader(
                        p);
                data.setWeather(weather);
                mAdapter.updateHeader(p, data);
            }
        } else if (method.equals(METHOD_HOME_INFO_V)) {
            VehicleHomeInfo.Response response = (VehicleHomeInfo.Response) entity;
            homeInfo = response.getData();
            if (homeInfo != null) {
//                Vehicle vehicle = (Vehicle) httpTask.getExtraParam(KEY_VEHICLE);

                homeInfo.setVehicle(mVehicle);

                int p = mAdapter.getHeaderPositionByViewType(HomeViewType.VT_BATTERY_MILLEAGE);
                if (HomeBatteryMilleageHolder.canShow(mVehicle)) {
                    HomeBatteryMilleageHolder.Data bmdata = new HomeBatteryMilleageHolder.Data(homeInfo);
                    if (p == -1) {
                        mAdapter.addHeader(mAdapter.getHeaderPosition(HomeViewType.VT_BATTERY_MILLEAGE,
                                mSortedHeaderViewTypes),
                                bmdata);
                    } else {
                        mAdapter.updateHeader(p, bmdata);

                    }
                } else {
                    mAdapter.removeHeader(p);
                }

                p = mAdapter.getHeaderPositionByViewType(VT_STATUS_ITEMS);
                HomeStatussHolder.Data data = new HomeStatussHolder.Data(homeInfo);
                if (HomeStatussHolder.isCanShow(mVehicle)) {
                    if (p == -1) {
                        mAdapter.addHeader(mAdapter.getHeaderPosition(VT_STATUS_ITEMS,
                                mSortedHeaderViewTypes),
                                data);
                    } else {
                        mAdapter.updateHeader(p, data);

                    }
                } else {
                    mAdapter.removeHeader(p);
                }

//                p = mAdapter.getHeaderPositionByViewType(HomeViewType.VT_WARNING_INFO);
                HomeWaringMessageHolder.Data wdata = new HomeWaringMessageHolder.Data(homeInfo);
                if (wdata.getHomeInfo().getAlarmInfo().getUnRead() <= 0) {
                    mBinding.tvNewMsg.setVisibility(View.GONE);
                }else{
                    mBinding.tvNewMsg.setVisibility(View.VISIBLE);
                    if(wdata.getHomeInfo().getAlarmInfo().getUnRead()>9){
                        mBinding.tvNewMsg.setText("...");

                    }else{
                        mBinding.tvNewMsg.setText(wdata.getHomeInfo().getAlarmInfo().getUnRead()+"");
                    }
                }
//                if (p == -1) {
//                    mAdapter.addHeader(mAdapter.getHeaderPosition(HomeViewType.VT_WARNING_INFO,
//                            mSortedHeaderViewTypes), wdata);
//                } else {
//                    mAdapter.updateHeader(p, wdata);
//                }

                //if (vehicle.getLight() == Vehicle.LIGHT_ON) {
                    p = mAdapter.getHeaderPositionByViewType(VT_ACTION);
                    HomeActionHolder.Data actionData = new HomeActionHolder.Data(homeInfo);
                    actionData.getHomeInfo().setLocation(location);
                    if (p == -1) {
                        mAdapter.addHeader(mAdapter.getHeaderPosition(VT_ACTION,
                                mSortedHeaderViewTypes),
                                actionData);
                    } else {
                        mAdapter.updateHeader(p, actionData);
                    }
                //} else {
                //    mAdapter.removeHeaderByViewType(VT_ACTION);
                //}

            }
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        //UniversalToastUtil.showFailedIconToastº(message);
        String method = httpTask.getMethod();
        if (METHOD_VEHICLE_LIST.equals(method)) {
            UniversalToastUtil.showFailedIconToast(HttpRequestUtil.getMessage(errorCode, message));
        } else if (METHOD_LOCATION.equals(method)) {
            //mAdapter.removeHeaderByViewType(VT_LOCATION);
//            Location location = new Location();
//            location.setDrivingState(Constant.VEHICLE_STATUS_OFFLINE);
//            Vehicle vehicle = (Vehicle) httpTask.getExtraParam(KEY_VEHICLE);
//            location.setVehicleCode(vehicle.getVehicleCode());
//            location.setVehicleNick(vehicle.getVehicleNick());
//            int p = mAdapter.getHeaderPositionByViewType(VT_LOCATION);
//            if (p == -1) {
//                mAdapter.addHeader(mAdapter.getHeaderPosition(VT_LOCATION, mSortedHeaderViewTypes),
//                                   location);
//            } else {
//                mAdapter.updateHeader(p, location);
//            }
            mBinding.setLocation(null);
            mBinding.tvAddress.setText(getString(R.string.no_gps_location));
            mBinding.gpsSignal.setSignal(0, R.drawable.gps_signal_bg_gray);
            initMap();
        } else if (METHOD_LAST_TRAVEL.equals(method)) {
            //mAdapter.removeChildByViewType(VT_ACTION);
            mAdapter.removeChildByViewType(VT_LAST_TRAVEL);
            int p = mAdapter.getChildPositionByViewType(HomeViewType.VT_WAIT_NEW_TRAVEL);
            if (p == -1) {
                mAdapter.addChild(1, new ViewType(HomeViewType.VT_WAIT_NEW_TRAVEL));
            }
        } else if (method.equals(UserRequest.METHOD_UPDATE_INFO)) {
            UniversalToastUtil.showFailedIconToast(HttpRequestUtil.getMessage(errorCode, message));
            closeLoadingDialog();
        } else if (method.equals(METHOD_HOME_INFO_V)) {
//            UniversalToastUtil.showToast(HttpRequestUtil.getMessage(errorCode, message));
            mAdapter.removeChildByViewType(VT_ACTION);
            mAdapter.removeChildByViewType(VT_STATUS_ITEMS);
            mAdapter.clear();
            homeInfo = null;
            mBinding.tvNewMsg.setVisibility(View.GONE);
            closeLoadingDialog();
        }
    }



    private void initMap() {
        String map = P.getString(KEY_MAP, MAP_DEFAULT);
        if (MAP_BAIDU.equals(map)) {
            initBaidu();
        } else if (MAP_GOOGLE.equals(map)) {
            initGoogle();
        }
    }

    private void initBaidu() {
        mBinding.bmapView.setVisibility(View.VISIBLE);
        mBinding.bmapView.showScaleControl(false);
        mBinding.bmapView.showZoomControls(false);

        BaiduMap map = mBinding.bmapView.getMap();
        map.setMyLocationEnabled(true);
//        map.setMyLocationConfiguration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING,
//                true,
//                BitmapDescriptorFactory.fromResource(
//                                                                           /*R.drawable
//                                                                           .location_icon_route_end*/
//                        0)));
        //map.setOnMapClickListener(mBadiuMapClickListener);
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(17.0f);
        map.setMapStatus(msu);
        //mLocationClient = new LocationClient(getApplicationContext());
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认gcj02
        //gcj02：国测局坐标；
        //bd09ll：百度经纬度坐标；
        //bd09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标

        option.setScanSpan(1000);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        //mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明

        //mLocationClient.registerLocationListener(mBaiduLocationListener = new
        // ElecAreaAddActivity.MyBaiduLocationListener());

        //mLocationClient.start();
        //mLocationClient.requestLocation();

//        afterInitMap();
        Location location = mBinding.getLocation();
        /*if (location.getDrivingState() == VEHICLE_STATUS_DRIVING) {
            baiduAnimateAndAddMarker(location.getLatitude(),
                                     location.getLongitude(),
                                     R.drawable.travel_start);
            mBaiduMarker = null;
        }*/
        mHandler.removeCallbacks(mGetCurrentLocationRunn);
        mHandler.post(mGetCurrentLocationRunn);

//        map.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
//            @Override
//            public boolean onMarkerClick(com.baidu.mapapi.map.Marker marker) {
//                Log.e("onMarkerClick","-----onMarkerClick-----");
//                if(location !=null){
//                    VehicleLocationActivity.start(getContext(), location);
//
//                }else{
////                    ToastUtil.showToast(getContext(),"当前车辆位置没有上报");
//                }
//                return false;
//            }
//        });

        map.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if(location !=null) {
                    VehicleLocationActivity.start(getContext(), location);
                }
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });

    }



    private Runnable mGetCurrentLocationRunn = new Runnable() {
        @Override
        public void run() {
            mCurrentLocation = LocationManager.getInstance().getLastLocation();
            updateUi();
        }
    };

    private void updateUi() {
        Location location = mBinding.getLocation();
//        if (!location.isGpsValid() || location
//                .getGpsTime() <= 0) {
//            mBinding.tvTime.setVisibility(View.GONE);
//        } else {
//            mBinding.tvTime.setVisibility(View.VISIBLE);
//        }
//
//        if (!location.isGpsValid()) {
//            mBinding.tvAddress.setText(R.string.no_gps_data);
//        }

//        // 信号
//        updateGpsSignal();
//        updateGsmSignal();

        String map = P.getString(KEY_MAP, MAP_DEFAULT);
        switch (map) {
            case MAP_BAIDU:
                if(location == null){
                    if(mCurrentLocation != null) {
                        baiduAnimateAndAddMarker(true,
                                mCurrentLocation.getLatitude(),
                                mCurrentLocation.getLongitude(),
                                R.drawable.location_64);
                    } else {
                        Gps gps = PositionUtil.gps84_to_bd09_byBaiduSdk(PositionUtil.BEIJING_LAT,
                                PositionUtil.BEIJING_LNG);
                        baiduAnimateAndAddMarker(true, gps.getWgLat(), gps.getWgLon(), 0);
                    }
                }else{
                    if (location.isGpsValid()) {
                        baiduAnimateAndAddMarker(true,
                                location.getLatitude(),
                                location.getLongitude(),
                                getTravelEndDrawable());
                    } else {
                        L.GL.w("车辆位置无效，显示用户当前位置");
                        if(mCurrentLocation != null) {
                            baiduAnimateAndAddMarker(true,
                                    mCurrentLocation.getLatitude(),
                                    mCurrentLocation.getLongitude(),
                                    0);
                        } else {
                            Gps gps = PositionUtil.gps84_to_bd09_byBaiduSdk(PositionUtil.BEIJING_LAT,
                                    PositionUtil.BEIJING_LNG);
                            baiduAnimateAndAddMarker(true, gps.getWgLat(), gps.getWgLon(), 0);
                        }
                    }
                }

                break;
            case MAP_GOOGLE:
                if(location == null){
                    if(mCurrentLocation != null) {
                        googleAnimateAndAddMarker(mCurrentLocation.getLatitude(),
                                mCurrentLocation.getLongitude(),
                                0);
                    } else {
                        //Gps gps = PositionUtil.gps84_To_Gcj02(PositionUtil.BEIJING_LAT,
                        //        PositionUtil.BEIJING_LNG);
                        //googleAnimateAndAddMarker(gps.getWgLat(), gps.getWgLon(), 0);
                        CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(1);
                        mGoogleMap.moveCamera(cameraUpdate);
                    }
                }else{
                    if (location.isGpsValid()) {
                        googleAnimateAndAddMarker(location.getLatitude(),
                                location.getLongitude(),
                                getTravelEndDrawable());
                    } else {
                        L.GL.w("车辆位置无效，显示用户当前位置");
                        if(mCurrentLocation != null) {
                            googleAnimateAndAddMarker(mCurrentLocation.getLatitude(),
                                    mCurrentLocation.getLongitude(),
                                    0);
                        } else {
                            //Gps gps = PositionUtil.gps84_To_Gcj02(PositionUtil.BEIJING_LAT,
                            //        PositionUtil.BEIJING_LNG);
                            //googleAnimateAndAddMarker(gps.getWgLat(), gps.getWgLon(), 0);
                            CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(1);
                            mGoogleMap.moveCamera(cameraUpdate);
                        }
                    }
                }

                break;
            default:
                break;
        }
    }

    /**
     * 移动到指定位置，并添加marker
     */
    private void baiduAnimateAndAddMarker(boolean animateTo,
                                          double latitude,
                                          double longitude,
                                          int positionDrawableRes) {
        if (latitude == 0 && longitude == 0) {
            L.GL.w("invalid location");
            return;
        }
        //Gps gps = PositionUtil.gps84_To_Bd09(latitude, longitude);
        Gps gps = new Gps(latitude-0.004, longitude);
        if (animateTo) {
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(new LatLng(gps.getWgLat(),
                    gps.getWgLon()));
            // 移动到某经纬度
            mBinding.bmapView.getMap().animateMapStatus(update);
        }

        if (positionDrawableRes > 0) {
            if (mBaiduMarker != null) {
                mBaiduMarker.remove();
            }
            //添加marker
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), positionDrawableRes);
            if (positionDrawableRes != R.drawable.travel_start && positionDrawableRes != R.drawable.travel_end && positionDrawableRes != R.drawable.travel_location) {
                bitmap = getDirectionBitmap(bitmap);
            }
            mBaiduMarker = mBinding.bmapView.getMap()
                    .addOverlay(new com.baidu.mapapi.map.MarkerOptions().anchor(
                            0.5f,
                            0.5f)
                            .position(
                                    new LatLng(
                                            latitude,
                                            longitude))

                            .icon(BitmapDescriptorFactory
                                    .fromBitmap(
                                            bitmap)));
            mBaiduMarker.setZIndex(6);
        }
    }

    private void googleAnimateTo(double latitude, double longitude) {
        if (latitude == 0 && longitude == 0) {
            L.GL.w("invalid location");
            return;
        }
        Gps _gps = /*PositionUtil.gps84_To_Gcj02(latitude, longitude)*/new Gps(latitude, longitude);
        // 移动到某经纬度
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new com.google.android.gms.maps.model.LatLng(
                _gps.getWgLat(),
                _gps.getWgLon()), 11);
        mGoogleMap.moveCamera(cameraUpdate);
    }

    private void googleAnimateAndAddMarker(double latitude,
                                           double longitude,
                                           int positionDrawableRes) {
        if (latitude == 0 && longitude == 0) {
            L.GL.w("invalid location");
            return;
        }
        Gps _gps = /*PositionUtil.gps84_To_Gcj02(latitude, longitude)*/new Gps(latitude, longitude);
        // 移动到某经纬度
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new com.google.android.gms.maps.model.LatLng(
                _gps.getWgLat(),
                _gps.getWgLon()), 11);
        mGoogleMap.moveCamera(cameraUpdate);

        if (positionDrawableRes > 0) {
            if (mGoogleMarker != null) {
                mGoogleMarker.remove();
            }
            //添加marker
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), positionDrawableRes);
            if (positionDrawableRes != R.drawable.travel_start && positionDrawableRes != R.drawable.travel_end && positionDrawableRes != R.drawable.travel_location) {
                bitmap = getDirectionBitmap(bitmap);
            }
            mGoogleMarker = mGoogleMap.addMarker(new MarkerOptions().icon(com.google.android.gms.maps.model.BitmapDescriptorFactory
                    .fromBitmap(bitmap))
                    .anchor(0.5f, 0.5f)
                    .position(new com.google.android.gms.maps.model.LatLng(
                            _gps.getWgLat(),
                            _gps.getWgLon())));
            mGoogleMarker.setZIndex(6);
        }
    }

    /**
     * GPS定位
     */
    private void updateGpsSignal() {
        if(location !=null){
            int count = location.getSignalSpan();
//            if (count < 4) {
//                count = 0;
//            } else if (count >= 4 && count < 6) {
//                count = 1;
//            } else if (count >= 6 && count < 8) {
//                count = 2;
//            } else if (count >= 8 && count < 10) {
//                count = 3;
//            } else if (count >= 10 && count < 12) {
//                count = 4;
//            } else if (count >= 12) {
//                count = 5;
//            }
            mBinding.gpsSignal.setSignal(count, R.drawable.gps_signal_bg_gray);
        }
    }

    /**
     * 基站定位
     */
    private void updateGsmSignal() {
        Location location = mBinding.getLocation();
        int count = location.getMcc();
        if (count < 0) {
            count = 0;
        }
        if (count > 5) {
            count = 5;
        }
//        mBinding.mccSignal.setSignal(count, R.drawable.gps_signal_bg_gray);
    }


    private int getTravelEndDrawable() {
        /*int d = R.drawable.travel_driving;
        Location location = mBinding.getLocation();
        if (location == null) {
            return d;
        }*/
        Location location = mBinding.getLocation();
        return VehicleDataBindingAdapter.getTravelLocationEndDrawable1(location == null ? -1 : location
                .getDrivingState());
    }

    private Bitmap getDirectionBitmap(Bitmap bitmap) {
        Location location = mBinding.getLocation();
        if (location == null) {
            return bitmap;
        }
        Matrix matrix = new Matrix();
        int bw = bitmap.getWidth();
        int bh = bitmap.getHeight();
        //matrix.postRotate((float) location.getDirection(), bw / 2, bh / 2);
        Bitmap bitmapNew = Bitmap.createBitmap(bitmap, 0, 0, bw, bh, matrix, true);
        //bitmap.recycle();
        return bitmapNew;
    }

    private void initGoogle() {
        mBinding.bmapView.setVisibility(View.GONE);
        mBinding.googleContainer.setVisibility(View.VISIBLE);
        com.google.android.gms.maps.SupportMapFragment mapFragment = (com.google.android.gms.maps.SupportMapFragment) getChildFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
        mGoogleMap.getUiSettings().setCompassEnabled(false);
        CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(15);
        mGoogleMap.moveCamera(cameraUpdate);
        afterInitMap();
        Location location = mBinding.getLocation();
        /*if (location.getDrivingState() == VEHICLE_STATUS_DRIVING) {
            googleAnimateAndAddMarker(location.getLatitude(),
                                      location.getLongitude(),
                                      R.drawable.travel_start);
            mGoogleMarker = null;
        }*/
        mHandler.removeCallbacks(mGetCurrentLocationRunn);
        mHandler.post(mGetCurrentLocationRunn);

        mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(com.google.android.gms.maps.model.LatLng latLng) {
                if(location !=null) {
                    VehicleLocationActivity.start(getContext(), location);
                }
            }
        });
    }

    private void afterInitMap() {
        try {
            String gpsDataJson = P.getString(KEY_GPS_DATA, "");
            if (!TextUtils.isEmpty(gpsDataJson)) {
                List<TravelGps> gps = new Gson().fromJson(gpsDataJson,
                        new TypeToken<List<TravelGps>>() {}.getType());
                if (gps != null && gps.size() > 1) {
                    showTravel(gps);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            L.GL.e(e);
        }
    }

    private void showTravel(List<TravelGps> travelGpss) {
        int gpsSize = travelGpss == null ? 0 : travelGpss.size();
        L.GL.d("gpsSize[%d]", gpsSize);
        if (gpsSize < 1) {
            L.GL.w("invalid gps data size");
            return;
        }
        String map = P.getString(KEY_MAP, MAP_DEFAULT);
        if (map.equals(MAP_BAIDU)) {
            mBinding.bmapView.getMap().clear();
            TravelGps startGps = travelGpss.get(gpsSize - 1);
            TravelGps endGps = travelGpss.get(0);
            mBinding.bmapView.getMap()
                    .addOverlay(new com.baidu.mapapi.map.MarkerOptions().icon(
                            BitmapDescriptorFactory.fromResource(R.drawable.travel_start))
                            .position(new LatLng(
                                    startGps.getLatitude(),
                                    startGps.getLongitude())))
                    .setZIndex(4);
            /*mBinding.bmapView.getMap()
                             .addOverlay(new com.baidu.mapapi.map.MarkerOptions().icon(
                                     BitmapDescriptorFactory.fromResource(R.drawable.travel_end))
                                                                                 .position(new LatLng(
                                                                                         endGps.getLatitude(),
                                                                                         endGps.getLongitude())))
                             .setZIndex(5);*/

            TravelGps travelGps;
            List<LatLng> latLngs = new ArrayList<>();
            //int seekProgress = gpsSize - mTravelProgress;
            for (int i = gpsSize - 1; i >= 0; i--) {
                travelGps = travelGpss.get(i);
                //经纬度都是0的舍弃
                if (travelGps.getLatitude() == 0f && travelGps.getLongitude() == 0f) {
                    continue;
                }
                //if (i >= seekProgress) {
                latLngs.add(new LatLng(travelGps.getLatitude(), travelGps.getLongitude()));
                //}
            }

            com.baidu.mapapi.model.LatLngBounds.Builder builder = new com.baidu.mapapi.model.LatLngBounds.Builder();
            builder.include(new LatLng(startGps.getLatitude(), startGps.getLongitude()));
            builder.include(new LatLng(endGps.getLatitude(), endGps.getLongitude()));

            L.GL.e("here1，latLngs[%d],gpsSize[%d]", latLngs.size(), gpsSize);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    L.GL.e("her3");
                    //if (!mUpdateByManual) {
//                    mBinding.bmapView.getMap()
//                                     .animateMapStatus(MapStatusUpdateFactory.newLatLngBounds(
//                                             builder.build(),
//                                             mBinding.bmapView.getWidth() - 100/*ScreenUtil.dp2px(
//                                                     VehicleLocationActivity.this,
//                                                     300)*/,
//                                             mBinding.bmapView.getHeight() - ScreenUtil.dp2px(
//                                                     VehicleLocationActivity.this,
//                                                     300)));
                    //}
                    L.GL.d("latLngs[%d]", latLngs.size());
                    if (latLngs.size() >= 2) {
                        OverlayOptions ooPolyline = new PolylineOptions().width(Constant.TRAVEL_LINE_WIDTH)
                                .color(ResUtil.getColor(
                                        R.color.travel_line_color))
                                .points(latLngs);
                        mBinding.bmapView.getMap().addOverlay(ooPolyline);
                    }
                }
            }, 500);
        } else if (map.equals(MAP_GOOGLE)) {
            if (mGoogleMap == null) {
                //mNeedShowTravel = true;
                return;
            }
            mGoogleMap.clear();
            TravelGps startGps = travelGpss.get(gpsSize - 1);
            TravelGps endGps = travelGpss.get(0);
            mGoogleMap.addMarker(new com.google.android.gms.maps.model.MarkerOptions().icon(com.google.android.gms.maps.model.BitmapDescriptorFactory
                    .fromResource(
                            R.drawable.travel_start))
                    .position(
                            new com.google.android.gms.maps.model.LatLng(
                                    startGps.getLatitude(),
                                    startGps.getLongitude())))
                    .setZIndex(4);
            /*mGoogleMap.addMarker(new com.google.android.gms.maps.model.MarkerOptions().icon(com.google.android.gms.maps.model.BitmapDescriptorFactory
                                                                                                    .fromResource(
                                                                                                            R.drawable.travel_end))
                                                                                      .position(
                                                                                              new com.google.android.gms.maps.model.LatLng(
                                                                                                      endGps.getLatitude(),
                                                                                                      endGps.getLongitude())))
                      .setZIndex(5);*/

            TravelGps travelGps;
            com.google.android.gms.maps.model.PolylineOptions polylineOptions = new com.google.android.gms.maps.model.PolylineOptions();
            for (int i = gpsSize - 1; i >= 0; i--) {
                travelGps = travelGpss.get(i);
                //经纬度都是0的舍弃
                if (travelGps.getLatitude() == 0f && travelGps.getLongitude() == 0f) {
                    continue;
                }
                polylineOptions.add(new com.google.android.gms.maps.model.LatLng(travelGps.getLatitude(),
                        travelGps.getLongitude()));
            }
            polylineOptions.width(Constant.TRAVEL_LINE_WIDTH)
                    .color(ResUtil.getColor(R.color.travel_line_color));
            mGoogleMap.addPolyline(polylineOptions);

            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            builder.include(new com.google.android.gms.maps.model.LatLng(startGps.getLatitude(),
                    startGps.getLongitude()));
            builder.include(new com.google.android.gms.maps.model.LatLng(endGps.getLatitude(),
                    endGps.getLongitude()));
            //CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(builder.build(), 100);
            //mGoogleMap.moveCamera(cu);
        }
    }



    @Override
    public void onActionTriggered(Object action) {
        if (action instanceof VehicleSelectPopWindow.SelectedVehicleChangedAction) {
            if(isBtConnectStatus){
                TBoxSDK.getInstance(null).disconnectDevice();
//                ToastUtil.showToast(getContext(),"正在断开连接");

            }
            VehicleSelectPopWindow.SelectedVehicleChangedAction vehicleChangedAction = (VehicleSelectPopWindow.SelectedVehicleChangedAction) action;
            Vehicle vehicle = vehicleChangedAction.getAction();
            showLoadingDialog("");
            mGeneralManager.getRequestManager()
                           .getUserRequest()
                           .updateInfo(null, vehicle.getVehicleCode(), null, null, this)
                           .addExtraParam(KEY_VEHICLE, vehicle)
                           .execute();
        } else if (action instanceof MapChangedAction || action instanceof UnitChangedAction) {
            getVehicleList();
        } else if (action instanceof DeleteVehicleAction || action instanceof AddVehicleAction || action instanceof EditVehicleAction) {
            getVehicleList();
        }
    }

    private HomeLocationHolder getLocationHolder() {
        int pos = mAdapter.getHeaderPositionByViewType(VT_LOCATION);
        if (pos != -1) {
            RecyclerView.ViewHolder viewHolder = mBinding.rcv.findViewHolderForAdapterPosition(pos);
            if (viewHolder instanceof HomeLocationHolder) {
                return (HomeLocationHolder) viewHolder;
            }
        }
        return null;
    }

    @Override
    public void onClick(View v) {
        int vid = v.getId();
        if (vid == R.id.ll_current_vehicle) {
            VehicleSelectPopWindow window = new VehicleSelectPopWindow(getContext(),
                    responseVehicle.getData());
            window.showAsDropDown(v,
                    ScreenUtil.dp2px(getContext(), 13),
                    ScreenUtil.dp2px(getContext(), 10));
        }else if(vid ==R.id.rl_warning){
            if(homeInfo != null){
                Vehicle vehicle = homeInfo.getVehicle();
                if (vehicle != null) {
                    VehicleWarningActivity.startActivity(getContext(), vehicle);
                }
            }
        }
//        else if(vid == R.id.container_map){
//            if(location !=null){
//                VehicleLocationActivity.start(getContext(), location);
//
//            }else{
//                ToastUtil.showToast(getContext(),"当前车辆位置没有上报");
//            }
//        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (compositeDisposable != null) {
            loopAtFixRate();
        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            getVehicleList();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (compositeDisposable != null) {
            compositeDisposable.clear();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ActionManager.getInstance().removeInterestedActions(this);
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
        }
    }

    @Override
    public int onGetWhereHomeTravelHolderIn() {
        return HomeTravelHolder.IN_HOME;
    }

    private static class InnerDecoration extends RecyclerView.ItemDecoration {
        private Context mContext;
        private int mSpace1;
        private int mSpace2;
        private int mSpace3;

        public InnerDecoration(Context context) {
            mContext = context;
            mSpace1 = ScreenUtil.dp2px(mContext, 8);
            mSpace2 = ScreenUtil.dp2px(mContext, 10);
            mSpace3 = ScreenUtil.dp2px(mContext, 10);
        }

        @Override
        public void getItemOffsets(@NonNull Rect outRect,
                                   @NonNull View view,
                                   @NonNull RecyclerView parent,
                                   @NonNull RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            int ap = parent.getChildAdapterPosition(view);
            if (ap == RecyclerView.NO_POSITION) {
                return;
            }
            int vt = parent.getAdapter().getItemViewType(ap);
            if (vt == VT_LOCATION || vt == VT_STATUS_ITEMS || vt == HomeViewType.VT_WARNING_INFO) {
                outRect.left = mSpace2;
                outRect.right = mSpace2;
                outRect.top = mSpace1;
            } else if (vt == VT_LAST_TRAVEL || vt == VT_ACTION || vt == HomeViewType.VT_WAIT_NEW_TRAVEL || vt == HomeViewType.VT_BATTERY_MILLEAGE) {
                outRect.left = mSpace2;
                outRect.right = mSpace2;
                outRect.top = mSpace1;
            }
        }
    }


    /**
     * 16进制转ASCII
     *
     * @param hex
     * @return
     */
    public static String hex2Str(String hex) {
        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {
            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);
            temp.append(decimal);
        }
        return sb.toString();
    }

}
